import React, { ReactElement, useEffect } from 'react'
import style from './ModalWindow.module.scss'

export interface IModalWindow {
  visible: boolean
  title: string
  content: ReactElement | string
  footer: ReactElement | string
  onClose: () => void
}
export default function ModalWindow ({visible = false, title, content, footer, onClose}: IModalWindow) {
  // создаем обработчик нажатия клавиши Esc
  const onKeydown = ({ key }: KeyboardEvent) => {
    switch (key) {
      case 'Escape':
        onClose()
        break
    }
  }

  useEffect(() => {
    document.addEventListener('keydown', onKeydown)
    return () => document.removeEventListener('keydown', onKeydown)
  })
  if (!visible) return null
  return (
    <div className={style.modal}>
      <div className={ style.modalDialog } onClick={e => {e.stopPropagation()}}>
        <div className={ style.modalHeader }>
          <h3 className={ style.modalTitle }>{title}</h3>
          <span className={ style.modalClose } onClick={onClose}>
            &times;
          </span>
        </div>
        <div className={ style.modalBody }>
          <div className={ style.modalContent }>{content}</div>
        </div>
        {footer && <div className={ style.modalFooter }>{footer}</div>}
      </div>
    </div>
  )
}
